import type { IScreenScaleOption } from '@/App.vue'
import { throttle } from 'lodash-es'
const useScreenScale = (option: IScreenScaleOption) => {
  const triggerScale = () => {
    // 设计稿：1920*1080
    // 目标适配：1920*1080 3840*2160(2*2) 7680*4320(4*2)

    // 1.设计稿尺寸
    const targetX = option.targetX || 1920
    const targetY = option.targetY || 1080
    const targetRatio = option.targetRatio || targetX / targetY

    // 2.拿到当前设备(浏览器)的宽度
    const currentX = document.documentElement.clientWidth || document.body.clientWidth
    const currentY = document.documentElement.clientHeight || document.body.clientHeight

    // 3.计算缩放比例
    let scaleRatio = currentX / targetX // 参照宽度进行缩放(默认情况)
    const currentRatio = currentX / currentY // 超高比率

    // 4.开始缩放网页
    // 超宽屏
    if (currentRatio > targetRatio) {
      scaleRatio = currentY / targetY // 参照高度进行缩放
      document.body.setAttribute(
        'style',
        `width:${targetX}px;height:${targetY}px;transform:scale(${scaleRatio}) translateX(-50%);left:50%`
      )
    } else {
      document.body.setAttribute(
        'style',
        `width:${targetX}px;height:${targetY}px;transform:scale(${scaleRatio})`
      )
    }
  }

  const triggerScaleThrottle = throttle(triggerScale, 300)

  onMounted(() => {
    triggerScale()
    window.addEventListener('resize', triggerScaleThrottle)
  })

  onBeforeUnmount(() => {
    window.removeEventListener('resize', triggerScaleThrottle)
  })
}

export default useScreenScale
